/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package mbean.admin.problem;

import java.io.IOException;
import javax.inject.Named;
import javax.enterprise.context.SessionScoped;
import java.io.Serializable;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.ejb.EJB;
import model.entity.Attendance;
import model.entity.Customerdemand;
import model.entity.Depot;
import model.entity.Problem;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import org.omnifaces.util.Faces;
import org.omnifaces.util.Messages;
import service.ICustomerdemandManager;
import service.InterfaceServiceLocal;
import utils.URL;
import utils.URLBuilder;

/**
 *
 * @author dingnangen
 */
@Named(value = "problemCreateMB")
@SessionScoped
public class ProblemCreateMB implements Serializable {

    @EJB(beanName = "ProblemManager")
    private InterfaceServiceLocal<Problem> problemManager;
    @EJB(beanName = "AttendanceManager")
    private InterfaceServiceLocal<Attendance> attendanceManager;
    @EJB(beanName = "CustomerdemandManager")
    private ICustomerdemandManager<Customerdemand> customerdemandManager;
    @EJB(beanName = "DepotManager")
    private InterfaceServiceLocal<Depot> depotManager;
    private Problem currentProblem;
    List<Depot> depotlist;
    private List<Attendance> attendancelist;
    private List<Customerdemand> customerdemandlist;

    /**
     * Creates a new instance of ProblemCreateMB
     */
    public ProblemCreateMB() {
    }

    public void init() {
        depotlist = depotManager.findAll();
        currentProblem = new Problem();

        currentProblem.setCreatedate(new Date());
        currentProblem.setFordate(new Date());
        currentProblem.setReadyTime(getDate("00:00"));
        currentProblem.setDueDate(getDate("23:59"));
        if (this.getDepotlist() != null && !this.getDepotlist().isEmpty()) {
            this.currentProblem.setIddepot(this.getDepotlist().get(0));
            refreshAttendancelist();
            refreshCustomerdemandlist();

        }
    }

    public void precreateProblem() {
        if (Faces.isPostback()) {
            System.out.println("isPostback");
            return;
        }
        init();

    }

    private boolean persisCurrentProblem() {
        try {
            if (customerdemandlist.size() < 1 || attendancelist.size() < 1) {
                throw new Exception("Null");
            }
            problemManager.create(currentProblem);
            Messages.create(Faces.getResourceBundle("bundle").getString("saveSuccess")).add();
            return true;
        } catch (Exception e) {
            if (e.getMessage().toString().equals("Null")) {
                Messages.create("配送车辆或订单不能为空!").add();
            } else {
                Messages.create(Faces.getResourceBundle("bundle").getString("failed")).add();
            }
            return false;
        }

    }

    public void create() {
        if (persisCurrentProblem()) {
            init();
        }

    }

    public void createAndcalculate() throws IOException {
        try {
            if (persisCurrentProblem()) {
                String submitCalculateState = submitCalculate(currentProblem);
                System.out.println("submitCalculateState:" + submitCalculateState);
                if (submitCalculateState.equals("0")) {
                    Messages.create(Faces.getResourceBundle("bundle").getString("saveSuccess")).add();
                    init();
                } else {
                    Messages.create("提交规划失败!").add();
                }
            }

        } catch (Exception e) {
            // Messages.create(Faces.getResourceBundle("bundle").getString("failed")).add();
        }

    }

    public void ondepotchange() {
        this.currentProblem.setAttendanceList(null);
        refreshAttendancelist();
        refreshCustomerdemandlist();

    }

    public void ontimechange() {
        this.currentProblem.setAttendanceList(null);
        this.currentProblem.setCustomerdemandList(null);
        refreshAttendancelist();
        refreshCustomerdemandlist();

    }

    public Problem getCurrentProblem() {
        return currentProblem;
    }

    public void setCurrentProblem(Problem currentProblem) {
        this.currentProblem = currentProblem;
    }

    public List<Depot> getDepotlist() {
        return depotlist;
    }

    public void setDepotlist(List<Depot> depotlist) {
        this.depotlist = depotlist;
    }

    private void refreshAttendancelist() {
        if (this.getDepotlist() == null || this.getDepotlist().isEmpty()) {
            return;
        }
        List p = new ArrayList();

        p.add(this.currentProblem.getFordate());
        p.add(this.currentProblem.getIddepot());

        attendancelist = attendanceManager.findAll("select a from Attendance a where a.attendancedate =?1 and a.iddepot=?2", p);

    }

    private void refreshCustomerdemandlist() {
        if (this.getDepotlist() == null || this.getDepotlist().isEmpty()) {
            return;
        }
        List p = new ArrayList();
//        Calendar calendar = new GregorianCalendar(2016, 8, 26, 0, 0, 0);

        p.add(this.currentProblem.getFordate());
//        p.add(this.currentProblem.getIddepot());
        p.add(this.currentProblem.getReadyTime());
        p.add(this.currentProblem.getDueDate());

        customerdemandlist = customerdemandManager.findAll("select cd from Customerdemand cd where cd.servicedate =?1 and cd.readyTime between ?2 and ?3", p);

    }

    public List<Attendance> getAttendancelist() {
        return attendancelist;
    }

    public void setAttendancelist(List<Attendance> attendancelist) {
        this.attendancelist = attendancelist;
    }

    public List<Customerdemand> getCustomerdemandlist() {
        return customerdemandlist;
    }

    public void setCustomerdemandlist(List<Customerdemand> customerdemandlist) {
        this.customerdemandlist = customerdemandlist;
    }

    private Date getDate(String str) {

        SimpleDateFormat formatter = new SimpleDateFormat("HH:mm");
        try {
            return formatter.parse(str);

        } catch (ParseException ex) {
            Logger.getLogger(ProblemCreateMB.class.getName()).log(Level.SEVERE, null, ex);
        }
        return new Date();
    }

    private String submitCalculate(Problem problem) {
        String url = new URLBuilder(URL.CALCULATE_URL).addParam("idproblem", "" + problem.getIdproblem()).build();
        OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder()
                .url(url)
                .build();
        Response response;
        try {
            response = client.newCall(request).execute();
            String result = response.body().string();
            System.out.println("response:" + result);
            return result;
        } catch (IOException ex) {
            Logger.getLogger(ProblemCreateMB.class.getName()).log(Level.SEVERE, null, ex);
        }
        return "1";

    }
}
